package com.hzw.saas.common.security.token;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.hzw.saas.common.security.pojo.dto.SaasUser;
import com.hzw.saas.common.util.Json;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 请求授权服务器，校验token是否合理, 暂时不用！！！
 * @author sonam
 * @sine 2021/10/29 3:05 下午
 */
@Slf4j
@Deprecated
@AllArgsConstructor
public class RemoteUserTokenService implements ResourceServerTokenServices {

    private final String checkTokenEndpointUrl;

    @Override
    public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException {
        // TODO 优化
        String response = HttpUtil.get(checkTokenEndpointUrl + "?token=" + accessToken);
        Map map = Json.parseObject(response, Map.class);
        List<String> authorities = Arrays.stream(map.get("authorities").toString().split(StrUtil.COMMA)).collect(Collectors.toList());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        authorities.forEach(authority -> {
            if(StrUtil.isNotBlank(authority)) {
                grantedAuthorities.add(new SimpleGrantedAuthority(authority));
            }
        });
        String clientId = map.get("clientId").toString();

        OAuth2Request request = new OAuth2Request(MapUtil.builder(new HashMap<String, String>()).put("clientId", clientId).map(),
            clientId,
            grantedAuthorities,
            true,
            Arrays.stream(map.get("scope").toString().split(StrUtil.COMMA)).collect(Collectors.toSet()),
            Arrays.stream(map.get("resourceIds").toString().split(StrUtil.COMMA)).collect(Collectors.toSet()),
            null,
            null,
            null);

        SaasUser saasUser = new SaasUser(map.get("userId").toString(),
            map.get("username").toString(),
            map.get("phoneNo").toString(),
            map.get("email").toString(),
            Integer.parseInt(map.get("type").toString()),
            "N/A",
            true,
            grantedAuthorities);

        return new OAuth2Authentication(request, new UsernamePasswordAuthenticationToken(saasUser, "N/A", grantedAuthorities));
    }

    @Override
    public OAuth2AccessToken readAccessToken(String accessToken) {
        throw new UnsupportedOperationException("Not supported: read access token");
    }

}
